package study.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * @author sunxuejian
 * @version 1.0
 * @date 2020/3/12 19:05
 */
@SpringBootConfiguration
@ConditionalOnClass({HttpClient.class})
@EnableConfigurationProperties(HttpClientProperties.class)
public class HttpClientAutoConfig {

	@Autowired
	HttpClientProperties httpClientProperties;

//	@Autowired
//	private LogbookHttpRequestInterceptor logbookHttpRequestInterceptor;
//
//	@Autowired
//	private LogbookHttpResponseInterceptor logbookHttpResponseInterceptor;

	@Bean
	@ConditionalOnMissingBean(HttpClient.class)
	public HttpClient httpClient() {
		// 构建requestConfig
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(httpClientProperties.getConnectTimeOut())//连接超时，默认-1
				.setSocketTimeout(httpClientProperties.getSocketTimeOut()).build();//默认-1
		HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
				//也就是连接池中每个HttpRoute(ip+端口)最多2个连接，总共最多20个连接。因此需要调整这2个参数来保证连接池中的连接充足，不等待过长时间才获得连接。
				.setMaxConnPerRoute(httpClientProperties.getMaxConnPerRoute())//单个主机的最大连接数，默认0
				.setMaxConnTotal(httpClientProperties.getMaxConnTotaol()) // 全局最大维持的连接数，默认0
				////使用logbook打印HTTP请求的日志
				//logbook.write.level=TRACE
				//logbook.format.style=http
//				.addInterceptorFirst(logbookHttpRequestInterceptor)
//				.addInterceptorFirst(logbookHttpResponseInterceptor)
				//使用长连接
				//.setConnectionReuseStrategy(new NoConnectionReuseStrategy())
				.build();
		return client;
	}
}
